<template>
  <q-page class="bg-grey-2">
    <q-header bordered class="bg-white text-dark q-py-sm">
      <q-toolbar class="flex justify-between">
        <q-btn label="取消" dense flat color="grey-8" @click="$router.back()" />
        <div class="text-bold text-h6">{{ config.label }}</div>
        <q-btn label="完成" unelevated dense color="primary" @click="submit" />
      </q-toolbar>
    </q-header>

    <div v-if="config.type === 'text'">
      <q-input class="full-width" filled v-model="consumer[config.name]" clearable />
    </div>
    <div v-else-if="config.type === 'select'">
      <list-select
        v-model="consumer[config.name]"
        :options="dictionary[config.dict]"
      />
    </div>
    <div v-else-if="config.type === 'image'">
      <cropper ref="avatar" v-model:img="consumer[config.name]" />
    </div>
    <div v-else-if="config.type === 'list'">
      <listTable :columns="config.columns" v-model:rows="consumer[config.name]" />
    </div>
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';
import listSelect from './components/listSelect.vue';
import cropper from './components/cropperAvatar.vue';
import listTable from './components/listTable.vue';

export default defineComponent({
  name: 'shopEditor',
  components: {
    cropper,
    listSelect,
    listTable
  },
  data () {
    return {
      config: {},
      consumer: {},
      dictionary: {}
    };
  },
  mounted () {
    this.consumer = this.$q.localStorage.getItem('consumer');
    this.config = this.$q.localStorage.getItem('editor');
    this.dictionary = this.$q.localStorage.getItem('dictionary') || {};
  },
  methods: {
    async submit () {
      const token = this.$q.localStorage.getItem('consumerToken');

      const formData = {};
      if (this.config.type === 'image') {
        await this.$refs.avatar.upload();
      }
      formData[this.config.name] = this.consumer[this.config.name];

      this.$axios.post('/c/shop/setConsumer', { formData }, { headers: { conAuth: token } }).then(({ data }) => {
        if (data.result === 'fail') {
          this.$q.notify({
            message: data.message || '设置失败',
            color: 'negative',
            icon: 'error',
            position: 'center',
            timeout: 4000
          });
        } else {
          this.$q.localStorage.set('consumer', this.consumer);
          this.$router.back();
        }
      });
    }
  }
});
</script>
